package Chapter5;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Datetime {

    public static void main(String[] args) throws Exception {

    	Datetime test = new Datetime();

        String strDate = test.addDate("M", "20120316", 1);
        System.out.println(strDate);
        
        strDate = test.addDate("D", "20120316", 3);
        System.out.println(strDate);
        
        strDate = test.addDate("Y", "20120316", -2);
        System.out.println(strDate);

    }

    public String addDate(String aa, String da, int dd) throws Exception {

        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = format.parse(da);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        if (aa.equals("Y")) {

            calendar.add(Calendar.YEAR, dd);

        } else if (aa.equals("M")) {

            calendar.add(Calendar.MONTH, dd);

        } else if (aa.equals("D")) {

            calendar.add(Calendar.DATE, dd);

        }

        return format.format(calendar.getTime());

    }

}


